import pandas as pd
import numpy as np
import os
from sklearn.cluster import KMeans, DBSCAN, Birch
import matplotlib.pyplot as plt
from sklearn import manifold
from keras.layers import *
from keras.models import *
from keras.callbacks import *
from sklearn.preprocessing import MinMaxScaler


def lstm_model(input_length, out_length):
    model = Sequential()
    # model.add(GRU(2, input_shape=(self.input_length, 1)))
    model.add(LSTM(2, input_shape=(input_length, 1), kernel_regularizer="l2"))
    # model.add(Dropout(0.2))
    # model.add(Dense(output_dim=out_length))
    model.add(Dense(units=out_length))
    model.compile(loss='mse', optimizer='adam')
    return model


def pre_train(data, input_length, output_length):
    min_val = min(data)
    max_val = max(data)
    data = (data - min_val) / (max_val - min_val)
    train_X = []
    train_Y = []
    valid_X = []
    valid_Y = []
    train_data = data[:int(len(data)*0.9)]
    valid_data = data[int(len(data)*0.9):]
    for i in range(len(train_data) - (input_length+output_length)):
        train_X.append(train_data[i:i+input_length])
        train_Y.append(train_data[i+input_length:i+input_length+output_length])
    for i in range(len(valid_data) - (input_length + output_length)):
        valid_X.append(valid_data[i:i + input_length])
        valid_Y.append(valid_data[i + input_length:i + input_length + output_length])

    train_X = np.array(train_X)
    train_Y = np.array(train_Y)
    valid_X = np.array(valid_X)
    valid_Y = np.array(valid_Y)
    train_X = np.reshape(train_X, (train_X.shape[0], train_X.shape[1], 1))
    valid_X = np.reshape(valid_X, (valid_X.shape[0], valid_X.shape[1], 1))
    return train_X, train_Y, valid_X, valid_Y


def plot_results(history, rows, subnum):
    """
            画出真实序列和预测序列
            :param history:
            :param subnum:
            :return:
            """
    plt.subplot(rows, 2, subnum)
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model train vs validation loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'validation'], loc='upper right')

